const jsonServer = require("json-server");
const md5 = require("md5");
const jwt = require("jsonwebtoken");
const {
  UsernameExistsError,
  EmailExistsError,
  PhoneExistsError,
  RoleNotExistError,
  LoginError,
} = require("../CustomError.class");
const server = jsonServer.create();
const router = jsonServer.router("./db.json");

server.use((req, res, next) => {
  router.db.read();
  next();
});

/**
 * GetUsers
 * @typedef {object} GetUsers
 * @property {string} username.required - 用户名校验，4到16位（字母，数字，下划线，减号） - _username
 * @property {string} password.required - 密码强度校验，最少6位，包括至少1个大写字母，1个小写字母，1个数字，1个特殊字符 - _password
 * @property {string} email.required - 邮箱 - _email
 * @property {string} phone.required - 手机号(mobile phone)中国(宽松), 只要是13,14,15,16,17,18,19开头即可 - _phone
 * @property {string} role.required - 角色
 */

/**
 * PatchUsers
 * @typedef {object} PatchUsers
 * @property {string} username - 用户名校验，4到16位（字母，数字，下划线，减号） - _username
 * @property {string} password - 密码强度校验，最少6位，包括至少1个大写字母，1个小写字母，1个数字，1个特殊字符 - _password
 * @property {string} email - 邮箱 - _email
 * @property {string} phone - 手机号(mobile phone)中国(宽松), 只要是13,14,15,16,17,18,19开头即可 - _phone
 * @property {string} role - 角色
 */

/**
 * PostLogin
 * @typedef {object} PostLogin
 * @property {string} username.required - 用户名
 * @property {string} password.required - 密码
 */

/* ***************************************** */

/**
 * GET /users
 * @tags users - 用户管理
 * @summary 获取用户列表
 * @security auth
 * @param {string} username.query - 用户名
 * @param {string} email.query - 邮箱
 * @param {string} phone.query - 手机
 * @param {string} role.query - 角色
 * @param {number} _page.query - 页码
 * @param {number} _limit.query - 每页条数
 * @param {string} _sort.query - 排序字段 - enum:id,username,email,phon,ctime,mtime
 * @param {string} _order.query - 排序规则 - enum:asc,desc
 * @return {array<GetUsers>} 200 - success response
 */

server.get("/users", (req, res, next) => {
  next();
});

/**
 * GET /users/{id}
 * @tags users
 * @summary 根据ID获取用户
 * @security auth
 * @param {number} id.path.required - 用户ID
 * @return {GetUsers} 200 - success response
 */
server.get("/users/:id", (req, res, next) => {
  next();
});

/**
 * POST /users
 * @tags users
 * @summary 添加用户
 * @security auth
 * @param {GetUsers} request.body.required - 用户对象 - application/json
 * @return {GetUsers} 201 - success response
 */
server.post("/users", (req, res, next) => {
  // 用户名重复验证
  if (router.db.get("users").find({ username: req.body.username }).value())
    throw new UsernameExistsError();

  // 邮箱重复验证
  if (router.db.get("users").find({ email: req.body.email }).value())
    throw new EmailExistsError();

  // 手机重复验证
  if (router.db.get("users").find({ phone: req.body.phone }).value())
    throw new PhoneExistsError();

  // 角色验证
  if (!router.db.get("rules").find({ group: req.body.role }).value())
    throw new RoleNotExistError();

  // 默认角色
  if (!req.body.role) req.body.role = "guest";

  // 密码加密
  req.body.password = md5(req.body.password);

  next();
});

/**
 * PATCH /users/{id}
 * @tags users
 * @summary 根据ID编辑用户
 * @security auth
 * @param {number} id.path.required - 用户ID
 * @param {PatchUsers} request.body - 用户对象 - application/json
 * @return {GetUsers} 200 - success response
 */
server.patch("/users/:id", (req, res, next) => {
  // 用户名重复验证
  if (router.db.get("users").find({ username: req.body.username }).value())
    throw new UsernameExistsError();

  // 邮箱重复验证
  if (router.db.get("users").find({ email: req.body.email }).value())
    throw new EmailExistsError();

  // 手机重复验证
  if (router.db.get("users").find({ phone: req.body.phone }).value())
    throw new PhoneExistsError();

  // 角色验证
  if (
    req.body.role &&
    !router.db.get("rules").find({ group: req.body.role }).value()
  )
    throw new RoleNotExistError();

  next();
});

/**
 * GET /users/exist
 * @tags users
 * @summary 判断字段是否存在
 * @security auth
 * @param {string} key.query.required - 字段名
 * @param {string} value.query.required - 值
 * @return {boolean} 200 - success response
 */
server.get("/users/exist", (req, res, next) => {
  // 手机重复验证
  let data = false;
  if (
    router.db
      .get("users")
      .find({ [req.query.key]: req.query.value })
      .value()
  ) {
    data = true;
  } else {
    data = false;
  }

  res.json({
    status: 200,
    success: true,
    data,
  });
});

/**
 * DELETE /users/{id}
 * @tags users
 * @summary 根据ID删除用户
 * @security auth
 * @param {number} id.path.required - 用户ID
 * @return {object} 200 - success response
 */
server.get("/users/:id", (req, res, next) => {
  next();
});

/**
 * POST /login
 * @tags users - 用户管理
 * @summary 登录
 * @param {PostLogin} request.body.required - 用户对象 - application/json
 * @return {GetUsers} 200 - success response
 */
server.post("/login", (req, res, next) => {
  const { username, password } = req.body;
  const r = router.db
    .get("users")
    .find({ username, password: md5(password) })
    .value();
  if (!r) throw new LoginError();
  res.json({
    status: 200,
    success: true,
    message: "login successful",
    data: "Bearer " + jwt.sign(r, process.env.JWT_KEY, { expiresIn: "10h" }),
  });
});
module.exports = () => server;
